// 兼容animationframe
window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame;
window.cancelAnimationFrame = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame;

var stats = new Stats();
stats.showPanel( 0 ); // 0: fps, 1: ms, 2: mb, 3+: custom
document.body.appendChild( stats.dom );

//
// var el = document.getElementById('image');
// var agree = 0, index = 0, times = 0, limit = 10,count = 0,easing = 0.3, v=0, a=0;
// (function drawFrame(){
//   stats.begin();
//     window.requestAnimationFrame(drawFrame);
//
//     // v = arr.reduce(function(d,sum) {return d+sum},0);
//     times++;
//     if(v > 0) {
//       times = 0;
//       // arr.length > 0 && arr.shift();
//       v = Math.max(0,v-0.02);
//     }
//     agree = (agree + v)%360;
//     console.log(agree);
//     el.style['transform'] = 'translate3d(0,0,0) rotate('+agree+'deg)';
//     // el.setAttribute('style','-webkit-transform:translate3d(0,0,0) rotate('+agree+'deg)')
//     // setStyle(el,{'webkitTransform':'translateZ(0) rotate('+agree+'deg)'});
//     stats.end();
//  }());
//
//  function setStyle(el,styles) {
//    for(var key in styles) {
//      el.style[key] = styles[key];
//    }
//  }
//
// function speedUp(btn) {
//   v = Math.round(Math.min(6,v+(v < 1.2 ? 1.2: 2/v))*100)/100;
//   console.log(v)
// }



var RotateEffect = {
  items: {},
  status: 0, // 0 : stop, 1: start
  easing: 0.02,
  accItem: null,
  times: 0,
  // opts: {root(optional),target()}
  init: function(opts) {
    var self = this,
        els = [].slice.call((opts.root || document).querySelectorAll(opts.target));
    this.items = {};
    this.afterDraw = opts.afterDraw;
    this.opts = opts;
    this.proxyAnimate = this._animate.bind(this);
    els.forEach(function(el) {
      var name = el.dataset['name'];
      self.items[name] = {
        name: name,
        el: el,
        degree: parseFloat(el.dataset['degree'] || opts['degree'] || 0), // 角度
        speed: parseFloat(el.dataset['speed'] || opts['speed'] || 0), //速度
        acc: opts.acc == name,
        stop: 0
      };
    });
    if(opts.acc) this.accItem = this.items[opts.acc];
    this._draw();
  },
  start: function() {
    if(this.accItem) {
      var v = this.accItem.speed;
      this.accItem.speed = Math.round(Math.min(4.8,v+(v < 1.2 ? 1.2: 2/v))*100)/100;
    }
    if(this.status == 0) {
      this.status = 1;
      this._animate();
    }
  },
  stop: function() {
    this.status = 0;
    window.cancelAnimationFrame(this.animateId)
  },
  _animate: function() {
    stats.begin();
    if(this.status == 1) {
      this.animateId = window.requestAnimationFrame(this.proxyAnimate);
    }
    this._draw();
    this.times ++;
    stats.end();
  },
  _draw: function() {
    console.log(new Date().getTime())
    for(var key in this.items) {
      var item = this.items[key];
      if(item.stop) continue; //停止动画
      if(item.acc && item.speed > 0) {
        item.speed = Math.max(0,item.speed - this.easing);
        if(item.speed == 0) this.status = 0; // 如果是可变速的，速度为0,则暂停
      }
      item.degree = (item.degree+item.speed)%360;
      item.el.setAttribute('style','transform:translate3d(0,0,0) rotate('+item.degree+'deg)')
      // item.el.style['transform'] = 'translate3d(0,0,0) rotate('+item.degree+'deg)';
    }
    console.log(new Date().getTime())
    this.afterDraw && this.afterDraw(this.items,this.accItem);
  }
}

var hideImgs = [4,5,6,7];
RotateEffect.init({
  target: '.animate',
  acc:'shoppingcart',
  speed:3,
  afterDraw: function(items,accItem) {
    for(var k in items) {
      var item = items[k];
      if(accItem.name != item.name) {
        if(!item.stop && item.speed < accItem.speed
          && item.degree - accItem.degree > 0
          && item.degree - accItem.degree < 10) {
          // addClass(item.el,'hide');
          item.el.className += ' hide';
          item.stop = 1;
          setTimeout((function(item){
            return function() {
              var i = parseInt(Math.random()*4)%4;
              item.el.src = 'good'+hideImgs[i]+'.png';
              var index = item.el.dataset['index'];
              item.el.dataset['index'] = hideImgs[i];
              hideImgs[i] = index;
              // removeClass(item.el,'hide');
              item.el.className = item.el.className.replace('hide','');
              // item.stop = 0;
              setTimeout(function(){item.stop = 0},150);
            }
          })(item),250);
        }
      }
    }
  }
});

function hasClass(obj, cls) {
    return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(obj, cls) {
    if (!this.hasClass(obj, cls)) obj.className += " " + cls;
}

function removeClass(obj, cls) {
    if (hasClass(obj, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        obj.className = obj.className.replace(reg, ' ');
    }
}

document.getElementById('start').addEventListener('click',function(e){
  RotateEffect.start();
  e.preventDefault();
  e.stopPropagation();
},false);

document.getElementById('stop').addEventListener('click',function(e){
  RotateEffect.stop();
  e.preventDefault();
  e.stopPropagation();
},false);
